import { Modal, Button, DatePicker, message, Divider, Select, Card, Col, Row, Form, Radio, List, Pagination ,Space,Tooltip} from 'antd';
import { PaperClipOutlined, DeleteOutlined, ExclamationCircleOutlined, FileTextOutlined } from '@ant-design/icons';
import React, { useState, useRef, useEffect } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';

import { queryDeviceAlarm, updateDeviceAlarm ,batchHandle,removeDeviceAlarm,batchRemoveDeviceAlarm} from '@/services/deviceAlarm';
import DetailForm from './components/DetailForm';
import UpdateForm from './components/UpdateForm';
import styles from '../style.less'
import './index.less'
import { paramToStringRemovePage } from '@/utils/utils';
import { GridContent } from '@ant-design/pro-layout';
import StandardFormRow from '@/components/StandardFormRow';
import TagSelect from '@/components/TagSelect';
const FormItem = Form.Item;
import { Link,useRequest, useModel } from 'umi';
import { queryDeviceTypeList } from '@/services/devicetype';
import { queryAreaTree } from '@/services/area';
const { confirm } = Modal;
const { Option } = Select;
const { RangePicker } = DatePicker;
import {alarmcode,transducerTripcode} from '@/utils/alarmcode-enum';
var btnwin = 0;




/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateDeviceAlarm(fields);
    hide();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

/**
 * 批量更新节点
 * @param fields
 */
 const batchHandleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await batchHandle(fields);
    hide();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

const Log: React.FC = (props) => {
   const { params } = props.match;
   const [form] = Form.useForm();

  const { initialState } = useModel('@@initialState');
  const { dicts } = initialState || {};
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [detailModalVisible, handleModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});
  const ref = useRef<ActionType>()
  const [EnumDefectSource, setEnumDefectSource] = useState([]);
  const [EnumAlarmType, setEnumAlarmType] = useState({});
  const [EnumAlarmLevel, setEnumAlarmLevel] = useState({});
  const [typeValues, setTypeValues] = useState<API.DictItem[]>([]);
  const [alarmType, setAlarmType] = useState<API.DictItem[]>([]);
  const [alarmLevel, setAlarmLevel] = useState<API.DictItem[]>([]);
  const [model, setModel] = useState<string>('2');
  const [loading, setLoading] = useState<boolean>(false);
  const [total, setTotal] = useState<number>(0);
  const [dateSourse, setDateSourse] = useState();
  const [pageSize, setPageSize] = useState<number>(10);
  const [current, setCurrent] = useState<number>(1);
  const [factArea, setFactArea] = useState([]);
  const [deviceType, setDeviceType] = useState([]);
  //级别
  const [tagAlarmTypeSel, setTagAlarmTypeSel] = useState( params.type!=undefined?[ params.type]: []);
  
  const [tagHandleTypeSel, setTagHandleTypeSel] = useState([]);
  const [optionFactAreaSel, setOptionFactAreaSel] = useState();
  const [optionDeviceTypeSel, setOptionDeviceTypeSel] = useState();
  const [rangePickerVal, setRangePickerVal] = useState([]);
  const [serText, setSerText] = useState();
  const [selectedRowKeys,setSelectedRowKeys] = useState<number[]>([]);



    
  //批量删除
  const batchRemove = async () => {
    const hide = message.loading('正在删除');
    try {
      await batchRemoveDeviceAlarm({ ids: selectedRowKeys.join(',')});
      setSelectedRowKeys([]);
      hide();
      message.success('删除成功，正在刷新！');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };


  const getSelectData = async () => {
    if (dicts) {
      setEnumDefectSource(dicts["5Enum"]);
      setEnumAlarmType(dicts["6Enum"]);
      setEnumAlarmLevel(dicts["8Enum"]);
      setTypeValues(dicts[5]);
      setAlarmType(dicts[6]);
      setAlarmLevel(dicts[8]);
    }
  };





  // 区域位置
  const OptionFactArea = (list) => {
    if (!list || list.length < 1) {
      return (
        <Option key={''} value={''}>
          没有找到选项
        </Option>
      );
    }
    return list.map((item) => (
      <Option key={item.value} value={item.value}>
        {item.title}
      </Option>
    ))
  }

  // 设备类型
  const OptionDeviceType = (list) => {
    if (!list || list.length < 1) {
      return (
        <Option key={''} value={''}>
          没有找到选项
        </Option>
      );
    }
    return list.map((item) => (
      <Option key={item.typeId} value={item.typeId}>
        {item.typeName}
      </Option>
    ))
  }

  const { run } = useRequest(() => getTableDate({}), { manual: true });
  useEffect(() => {
    run();
  }, [pageSize, current, tagAlarmTypeSel,tagHandleTypeSel,optionFactAreaSel,optionDeviceTypeSel,rangePickerVal]);


  async function getTableDate(param) {
 
    setLoading(true);
    //报警记录
    let tabledate = await queryDeviceAlarm(
      {
        current: current,
        pageSize: pageSize,
        selFactArea:optionFactAreaSel,
        selAlarmType: tagAlarmTypeSel,
        selHandleType: tagHandleTypeSel,
    
        seldeviceType: optionDeviceTypeSel,
        selRangePicker: rangePickerVal,
        serText: serText,
        // ...searchDate,
        // selAlarmType:[params[0]],
        ...param

      });
 
    setDateSourse(tabledate.data);
    setTotal(tabledate.total);
    setLoading(false);
  }


  async function getFactArea() {
    setLoading(true);
    //设备区域
    let tabledate = await queryAreaTree();
    setFactArea(tabledate);
    setLoading(false);

  }

  async function getSysDeviceType() {
    setLoading(true);
    //设备类型
    let tabledate = await queryDeviceTypeList();
    setDeviceType(tabledate);
    setLoading(false);
  }

  useEffect(() => {
    getSelectData();
    getFactArea();
    getSysDeviceType()
  }, []);


  const  getAlarmMsg=  (val)=>{

   // if(val.attrId!=null){
      return val.alarmValue;
    // }else {
    //   let str= alarmcode[val.alarmValue];
    //  if(!str){
    //     str= transducerTripcode[val.alarmValue];
    //  }
  
    //  return str;
    // }
}

  const columns: ProColumns[] = [

    {
      title: '报警时间',
      dataIndex: 'alarmTime',
      valueType: 'dateTime',
      search: false,
    },

    
    {
      title: '报警设备',
      dataIndex: 'deviceName',
      search: false,

    },
    {
      title: '报警规则',
      dataIndex: 'alarmName',
      search: false,

    },
    
    {
      title: '报警变量',
      dataIndex: 'browseName',
      search: false,
    },
    // {
    //   title: '报警类别',
    //   dataIndex: 'alarmType',
    //   valueEnum: EnumAlarmType,
    //   search: false,
    // },
    {
      title: '报警级别',
      dataIndex: 'alarmLevel',
      valueEnum: EnumAlarmLevel,
      search: false,
    },
    {
      title: '报警数值',
      dataIndex: 'alarmValue',
      search: false,
      render: (text, record) => (
       <Space size="middle">
        {getAlarmMsg(record)}
       </Space>
      ),
    },
    {
      title: '信息来源',
      dataIndex: 'defectSource',
      valueEnum: EnumDefectSource,
      search: false,
    },
    {
      title: '处置建议',
      search: false,
      width: 240,
      dataIndex: 'handleOpinions',
      render: (text, record) => (
        <Space size="middle"  className={styles.textOverflow}>
          <Tooltip placement="topLeft" title={text} arrowPointAtCenter>
           {text}
          </Tooltip>
        </Space>
       ),
    },
  
    {
      title: '处置状态',
      dataIndex: 'state',
      valueEnum: {
        0: { text: '未处置' },
        1: { text: '已处置' },
      },
      search: false,
    },
    // {
    //   title: '报警处置信息',
    //   dataIndex: 'alarmAnswer',
    //   search: false,
    // },
    // {
    //   title: '报警处置信息',
    //   dataIndex: 'alarmHandle',
    //   search: false,
    // },
    // {
    //   title: '处置人',
    //   dataIndex: 'userName',
    //   search: false,
    // },
    // {
    //   title: '处置时间',
    //   dataIndex: 'handleTime',
    //   valueType: 'dateTime',
    //   search: false,
    // },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => (
        <>
          <a
            key="select"
            onClick={async () => {
            
              handleModalVisible(true);
              setFormValues(record);
            }}
          >详情
          </a>
          {record.state==0?
          (<>
            <Divider type="vertical" />
            <a
              onClick={async () => {
                handleUpdateModalVisible(true);
                setFormValues(record);
              }}
            >处置
            </a>
          </>):null}
          <Divider type="vertical" />
          <a onClick={() => {
            confirm({
              title: '您确定要删除吗?',
              icon: <ExclamationCircleOutlined />,
              async onOk() {
                await removeDeviceAlarm({id:record.id});
                await  getTableDate({});
              },
              onCancel() {
                console.log('Cancel');
              },
            });
          }}
          >
            删除
          </a>
        </>
      )
    }]

  function onChangeSel(e) {
    setModel(e.target.value);
  }

  async function onChange(c, ps) {
    if (!loading) {
      setCurrent(c);
      setPageSize(ps);
    }
  }

  function chuZhi(record) {
    btnwin=1
    handleUpdateModalVisible(true);
    setFormValues(record);
  }

  function getDetail(record) {
    if(btnwin==0){
      handleModalVisible(true);
    }
    setFormValues(record);
  }


  function Tops() {
  
    const optionsSel = [
      { label: '表格模式', value: '2' },
      { label: '陈列模式', value: '1' },
    
    ];
    return (
      <Card bordered={false}>
        <Form
          layout="inline"
          form={form}
          initialValues={{
            selAlarmType: tagAlarmTypeSel,
          }}
        

          onReset={async (fieldsValue: any) => {
            setPageSize(10);
            setCurrent(1);
            setTagAlarmTypeSel([]);
            setTagHandleTypeSel([]);
            setOptionFactAreaSel();
            setOptionDeviceTypeSel();
            setRangePickerVal([])
            form.resetFields();
          }}
        >
            <StandardFormRow title="其它选项">
            <Row style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Col style={{ flex: 1 }}>
                <Row>
                    {/* <Col style={{ width: '15%', marginRight: '15px' }}>
                  <FormItem
                      name="serText"
                    >
                      <Input placeholder="请输入报警信息"  onChange={(e)=>{ setSerText(e.target.value);}}  autoComplete='off' style={{ marginRight: '15px' }} />
                    </FormItem>
                  </Col> */}
                  <Col style={{ width: '10%', marginRight: '15px' }}>
                    <FormItem name="selFactArea" >
                      <Select placeholder="区域位置"  onChange={(e)=>{ setOptionFactAreaSel(e);}}  bordered={false} style={{ width: '100%' }}>
                        {OptionFactArea(factArea)}
                      </Select>
                    </FormItem>
                  </Col>
                  <Col style={{ width: '10%', marginRight: '15px' }}>
                    <FormItem name="seldeviceType">
                      <Select placeholder="设备类型"  onChange={(e)=>{ setOptionDeviceTypeSel(e);}}  bordered={false} style={{ width: '100%' }} >
                        {OptionDeviceType(deviceType)}
                      </Select>
                    </FormItem>
                  </Col>
                  <Col>
                    <FormItem name="selRangePicker">
                      <RangePicker   onChange={(e)=>{ setRangePickerVal(e.length == 0 ? [] : [e[0].format('YYYY-MM-DD'), e[1].format('YYYY-MM-DD')]) ;}} />
                    </FormItem>
                  </Col>
                </Row>
              </Col>
              <Col>
              <Row>
                  <Radio.Group
                    options={optionsSel}
                    onChange={onChangeSel}
                    value={model}
                    optionType="button"
                    buttonStyle="solid"
                  />
                </Row>
              </Col>
            </Row>
          </StandardFormRow>
          <StandardFormRow title="报警级别" grid style={{ paddingBottom: 11 }}>
            <Row gutter={[16, 24]} justify="space-between">
              <Col >
                <FormItem name="selAlarmType" >
                  <TagSelect expandable={false}   onChange={(e)=>{ setTagAlarmTypeSel(e);}}  >
                    {alarmLevel.map((item) => (
                      <TagSelect.Option value={item.dictCode}>{item.dictValue}</TagSelect.Option>
                    ))}
                    {/* <TagSelect.Option value='601'>高高报警</TagSelect.Option>
                    <TagSelect.Option value='602' checked>中报警</TagSelect.Option>
                    <TagSelect.Option value='603'>低低报警</TagSelect.Option> */}
                  </TagSelect>
                </FormItem>
              </Col>
              <Col >
               
              </Col>
            </Row>
          </StandardFormRow>
          <StandardFormRow title="处置类型" grid style={{ paddingBottom: 11, color: '#fff' }}>
            <Row gutter={[16, 24]} justify="space-between">
              <Col >
                <FormItem name="selHandleType" >
                  <TagSelect expandable defaultValue={[]} onChange={(e)=>{ setTagHandleTypeSel(e);}}>
                    <TagSelect.Option value="0">未处置</TagSelect.Option>
                    <TagSelect.Option value="1">已处置</TagSelect.Option>
                  </TagSelect>
                </FormItem>
              </Col>
              <Col>
                <Button type="primary" icon={<DeleteOutlined />} style={{ marginRight: '15px' }}   className={styles.delBtn}  htmlType="reset">重置</Button>
                {/* <Button type="primary" icon={<SearchOutlined />} style={{ marginRight: '15px' }} className={styles.addBtn} htmlType="submit">搜索</Button> */}
                <a href={"/api/exportAlarmRecordExcel?" + paramToStringRemovePage()}>
                  <Button type="primary" icon={<PaperClipOutlined />}  className={styles.exportBtn} >导出</Button></a>
              </Col>
            </Row> 
          </StandardFormRow> 
        
        </Form>
      </Card>
    )
  };


  
  const list = dateSourse || [];
  const cheList = list && (
    <GridContent className={styles.baojing}>
      <React.Fragment>
        <List
          rowKey="id"
          loading={loading}
          dataSource={dateSourse}
          renderItem={(item) => (
            <List.Item style={{ borderBottom: '0px', display: 'block', padding: '0  24px' }} onClick={() => getDetail(item)}>
               {/* <Link   to={`/alarm/record/details/${item.id}`}    > */}
              <div className={styles.listblock} >
                <Row className={styles.top}>
                  <Col>
                    <span className={styles.time}>{item.alarmTime}</span>
                  </Col>
                </Row>
                <Row>
                  <Col style={{ width: '10%' }}>
                    <div className={item.alarmLevel == '801' ? [styles.itemlabel, styles.block2].join(' ') :item.alarmLevel == '802'  ? [styles.itemlabel, styles.block3].join(' ') : [styles.itemlabel, styles.block4].join(' ')} >
                      {EnumAlarmLevel[item.alarmLevel ]}
                    </div>
                  </Col>
                  <Col className={styles.col2}>
                    <Row style={{ justifyContent: 'space-between' }} style={{height:'90px'}}>
                      <Col className={styles.colwd}>设备名称：{item.deviceName}</Col>
                      <Col className={styles.colwd}>设备位号：{item.deviceNo}</Col>
                      {/* <Col className={styles.colwd}>所在区域：{item.areaName}</Col>
                      
                      <Col className={styles.colwd}>所在位置：{item.devicePosition}</Col> */}
                      
                     {item.ruleId==null?null: <Col className={styles.colwd}>报警规则：{item.alarmName}</Col>}
                     {item.attrId==null?null: <Col className={styles.colwd}>报警变量：{item.browseName}</Col>}
                      
                      <Col className={styles.colwd}>报警数值：{getAlarmMsg(item)}</Col>
                      {/* <Col className={styles.colwd}>报警类别：{EnumAlarmType[item.alarmType ]}</Col> */}
                    
                    {/* </Row>
                    <Row> */}
                       <Col className={styles.colwd}>信息来源：{EnumDefectSource[item.defectSource]}</Col>
                       <Col className={styles.colwd}>所在区域：{item.areaName}</Col>
                      
                      <Col className={styles.colwd}>所在位置：{item.devicePosition}</Col>
                      {/* <Col className={styles.colwd}>联系电话：{item.supplierPhone}</Col> */}
                    </Row>
                  </Col>
                  <Col style={{ width: '15%', display: 'flex', justifyContent: 'flex-end' }}>
                     {item.state==0? <Button size="small" type="primary" icon={<FileTextOutlined />} className={item.state==1?styles.btnchuz:styles.primaryBtnBg} onClick={() => chuZhi(item)}>处置</Button>:null }  
                  </Col>
                </Row>
              </div>
              {/* </Link> */}
            </List.Item>
          )}
        />
      </React.Fragment>
    </GridContent >
  );

  const onSelectChange = async (sKeys ) => {
    setSelectedRowKeys(sKeys);
  };

  const rowSelection = {
    // getCheckboxProps: (record: any) => ({
    //   disabled: record.state === 1, // Column configuration not to be checked
    // }),
    selectedRowKeys,onChange: onSelectChange
  };


  return (
    <>
      <Tops />
      {model == '1' ? cheList :
        <ProTable
          actionRef={ref}
          columns={columns}
          options={false}
          dateFormatter="string"
          dataSource={dateSourse}
          rowKey="id"
          search={{
            optionRender: false,
            collapsed: false,
          }}
          headerTitle=""
          pagination={false}
          tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
            <Space size={24}>
              <span>
                已选 {selectedRowKeys.length} 项
                <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                  取消选择
                </a>
              </span>
            </Space>
          )}

     
          tableAlertOptionRender={(selected) => {
            return (
              <Space size={16}>
                <a  onClick={() => { 
                  handleUpdateModalVisible(true);
                  // setFormValues(record);
                }}
                 >批量处置</a>
                   <a  onClick={() => {
                    confirm({
                      title: '您确定要批量删除吗?',
                      icon: <ExclamationCircleOutlined />,
                      async onOk() {
                        await batchRemove();
                        await  getTableDate({});
                      },
                      onCancel() {
                        console.log('Cancel');
                      },
                    });
                  }} >批量删除</a>
              </Space>
            );
          }}
          rowSelection={{...rowSelection}}
     
        />}
      <Row style={{ display: 'flex', flexDirection: 'row', justifyContent: 'flex-end', marginRight: '20px' }} >
        <Pagination
          size="small"
          total={total}
          defaultPageSize={pageSize}
          onChange={onChange}
          current={current}
          showSizeChanger
        />
      </Row>

     
      {formValues && Object.keys(formValues).length&&EnumDefectSource?(
        <DetailForm
          onCancel={() => {
            handleModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={detailModalVisible}
          values={formValues}
          alarmSource={EnumDefectSource}
          alarmLevel={EnumAlarmLevel}
        />
      ) : null}

      {(formValues && Object.keys(formValues).length )||selectedRowKeys.length>0? (
        <UpdateForm
          onSubmit={async (value) => {
         
            
            btnwin=0

            let success=false;
            if(value.id==null){
              value.ids=selectedRowKeys.join(',');
              setSelectedRowKeys([]);
              success = await batchHandleUpdate(value);
            }else{
              success = await handleUpdate(value);
            }
           
            if (success) {
              getTableDate({});
              handleUpdateModalVisible(false);
              setFormValues({});
           
              if (ref.current) {
                ref.current.clearSelected();
                ref.current.reload();
              }
            }
          }}
          onCancel={() => {
            btnwin=0
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
        />
      ) : null}
    </>
  );
};

export default Log;